namespace SinaFinance
{
    using System;
    using System.Diagnostics;
    using System.Net.NetworkInformation;
    using System.Windows;
    using System.Windows.Browser;

    public partial class App : Application
    {
        //private bool _contentLoaded;

        public App()
        {
            base.Startup += new StartupEventHandler(this.Application_Startup);
            base.Exit += new EventHandler(this.Application_Exit);
            base.UnhandledException += new EventHandler<ApplicationUnhandledExceptionEventArgs>(this.Application_UnhandledException);
            this.InitializeComponent();
        }

        private void Application_Exit(object sender, EventArgs e)
        {
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                base.RootVisual = new MainPage();
            }
            else
            {
                base.RootVisual = new OfflinePage();
            }
        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            Action action = null;
            if (!Debugger.IsAttached)
            {
                e.Handled = true;
                if (action == null)
                {
                    action = delegate {
                        this.ReportErrorToDOM(e);
                    };
                }
                Deployment.Current.Dispatcher.BeginInvoke(action);
            }
        }

        //[DebuggerNonUserCode]
        //public void InitializeComponent()
        //{
        //    if (!this._contentLoaded)
        //    {
        //        this._contentLoaded = true;
        //        Application.LoadComponent(this, new Uri("/SinaFinance;component/App.xaml", UriKind.Relative));
        //    }
        //}

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string str = (e.ExceptionObject.Message + e.ExceptionObject.Message).Replace('"', '\'').Replace("\r\n", @"\n");
                HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + str + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}
